<template>

    <!-- 支付弹窗 -->
    <UxDialog class="order-payment" :status="status" :visible="!!this.status" :can-close="false">

        <!-- 币种提醒 -->
        <div class="order-payment-currency" v-show="status == 'currency'">

            <div class="order-payment-close" @click="onClose()"><svg-icon name="dialog-close-medium" /></div>

            <figure><img src="@/assets/images/payment-currency.png" alt=""></figure>

            <h2>Tips</h2>
            <p>Please note that the currency you have selected to view on our website has been converted from USD using
                the current exchange rate. All payments will still be processed in USD.</p>

            <label>
                <input type="checkbox" v-model="state">
                <i class="iconfont icon-gougou"></i>
                <span>Don't show this again.</span>
            </label>

            <button type="primary" @click="currencyConfirm()">Got it</button>
        </div>

        <!-- 初始化状态，或是正在调用支付接口 -->
        <div class="order-payment-before" v-show="/init|before|paying/.test(status)" :currency="currency"
             :class="{ 'no-wallet': is_wallet != 2 }">

            <div class="order-payment-close" @click="onClose()"><svg-icon name="dialog-close-medium" /></div>

            <div class="order-payment-before-currency">
                <em>Order Total: </em>
                <CommonCurrencyRate :price="option.amount" />
                <span>Current exchange rate: 1 USD = {{ rate.toFixed(2) }}{{ currency }} </span>
            </div>

            <h3>
                <img src="https://img.podpartner.com/static/images-20230202/payment-mask.png" alt="" />
                <span v-text="'Total cost: USD ' + getPriceFormat(option.amount)"></span>
            </h3>

            <!-- 钱包支付 -->
            <OrderPaymentWallet ref="wallet" :option="option" @statusChange="statusChange($event)"
                                v-if="is_wallet == 2" />

            <div class="order-payment-other">
                <h4>Other methods</h4>

                <div class="order-payment-group">
                    <!-- paypal支付 -->
                    <!-- <OrderPaymentPaypal v-if="option.amount <= 300000" :option="option"
                        @statusChange="statusChange($event)" /> -->

                    <!-- payoneer支付 -->
                    <OrderPaymentPayoneer :option="option" @statusChange="statusChange($event)" />
                    <!-- <OrderPaymentPayoneer v-if="option.action == 'single' " :option="option" @statusChange="statusChange($event)" /> -->

                    <!-- 银行卡支付 -->
                    <!-- <OrderPaymentCard v-else :option="option" @statusChange="statusChange($event)" /> -->

                </div>
                <p>Your data is safe - we don't store your card or billing method details.</p>
            </div>

            <UxLoading v-show="status == 'before'" />
        </div>

        <!-- 支付成功 -->
        <div class="order-payment-success" v-if="status == 'success'">
            <figure>
                <img src="https://img.podpartner.com/static/images-20230202/payment/order-payment-success.png" alt="">
                <strong>Payment successful</strong>
                <span v-text="'Amount paid：USD ' + getPriceFormat(option.amount)"></span>
            </figure>
            <button type="primary" @click="status = 'batchtip'" v-if="batchtip">OK</button>
            <button type="primary" @click="onClose()" v-else>OK</button>
        </div>

        <!-- 支付失败 -->
        <div class="order-payment-failure" v-if="status == 'failure'">

            <div class="order-payment-close" @click="onClose()"><svg-icon name="dialog-close-medium" /></div>
            <figure>
                <img src="https://img.podpartner.com/static/images-20230202/payment/payfailure.png" alt="">
                <strong>Payment failed</strong>
                <span v-text="state"></span>
            </figure>
            <button type="primary" @click="onClose()">OK</button>
        </div>

        <!-- 网络异常，可重新支付 -->
        <div class="order-payment-network" v-if="status == 'network'">
            <div class="order-payment-close" @click="onClose()"><svg-icon name="dialog-close-medium" /></div>
            <figure>
                <img src="https://img.podpartner.com/static/images-20230202/payment/order-payment-network.png" alt="">
                <strong>The connection has timed out.</strong>
            </figure>
            <button type="primary" @click="state && state()">Try again</button>
        </div>

        <!-- 库存不足 -->
        <OrderPaymentOutOfStock v-if="status == 'stock'" :stocks="stocks" @close="onClose()" />

        <!-- 黑名单用户 -->
        <OrderPaymentBlackUser v-show="status == 'blackuser'" @close="onClose()" />

        <!-- 1小时内支付>=3时提醒批量支付 -->
        <OrderPaymentBatchTip v-show="status == 'batchtip'" @close="onClose()" />

    </UxDialog>
</template>
<script>
import { mapGetters, mapState } from "vuex";
export default {
    name: "OrderPaying",
    data () {
        return {
            status: "", // init|before|paying|success|failure|network
            state: null,
            stocks: [], // 库存不足
            batchtip: false,
            option: {
                payment: "paypal",
                amount: 0,
                codes: "",
                product: [],
                billing: null,
                action: 'single', // single|batch|recharge
            },
        };
    },
    computed: {
        ...mapState({
            currency: 'currency',
            rate: 'rate',
        }),
        ...mapGetters("user", {
            getPopupAccess: 'getPopupAccess',
        }),
        ...mapState('user', {
            is_wallet: 'is_wallet',
        })
    },
    methods: {
        // 打开界面
        open (option = {}) {
            this.option.amount = option.amount || 0;
            this.option.codes = option.codes || "";
            this.option.action = /single|batch|wallet/.test(option.action) ? option.action : 'single';
            this.option.product = option.product || [];
            this.option.shipping = option.shipping || null;

            // 支付货币提醒
            if (this.currency != 'USD' && !this.getPopupAccess.payment_switching_currency) {
                this.status = 'currency';
                this.state = false;
            } else {
                this.status = "init";
                this.state = null;
            }

            // 111


            // 一：主流程支付验证
            // 01.【下单页，钱包余额足够时支付成功】（已验）
            // 02.【下单页，钱包余额不足时paypal充值并支付成功】（已验）
            // 03.【下单页，钱包余额不足时ocean充值并支付成功】（已验）
            // 04.【下单页，paypal支付成功】（已验）
            // 05.【下单页，ocean支付成功】（已验）
            // 06.【订单详情页，钱包余额足够时支付成功】（已验）
            // 07.【订单详情页，钱包余额不足时paypal充值并支付成功】（已验）
            // 08.【订单详情页，钱包余额不足时ocean充值并支付成功】（已验）
            // 09.【订单详情页，paypal支付成功】（已验）
            // 10.【订单详情页，ocean支付成功】（已验）
            // 11.【批量支付，钱包余额足够时支付成功】（已验）
            // 12.【批量支付，钱包余额不足时paypal充值并支付成功】（已验）
            // 13.【批量支付，钱包余额不足时ocean充值并支付成功】（已验）
            // 14.【钱包页，paypal充值成功】（已验）
            // 15.【钱包页，ocean充值成功】（已验）


            // 二：订单业务流程相关异常
            // 01.【下单页，生成订单失败】（已验）
            // -- 点击钱包支付：提示网络失败，重新生成订单
            // -- 点击paypal支付：提示网络失败，重新生成订单
            // -- 点击ocean支付：提示网络失败，重新生成订单
            // 02.【下单页，生成重复订单问题】（已验）
            // -- 生成订单成功后，取消支付，再次支付：不再次生成订单
            // -- 生成订单成功后，取消支付，刷新页面，再次支付：再生成一个订单？
            // 03.【下单页，订单多次支付问题】（已验）
            // -- paypel支付成功后，未接到支付成功状态关闭paying：跳转到订单列表页
            // -- ocean支付时，跳转3d验证界面，然后在主界面退出pending状态：关掉支付窗口
            // 04.【下单页，订单支付后跳转】（已验）
            // -- 支付成功后点击OK按钮：跳转
            // -- paypel支付为pending状态后关闭：跳转
            // -- 点击钱包支付后取消支付：跳转
            // -- 点击ocean支付后取消支付：跳转
            // 05.【订单详情页，不是未支付状态下支付】（已验）
            // -- 点击钱包支付(余额充足)：重新加载页面
            // -- 点击钱包支付(余额不足)，paypal充值后支付：重新加载页面
            // -- 点击paypal支付：重新加载页面
            // -- 点击paypal支付，完成后退出pending状态，返回到详情页面，等一会再点击ocean支付：支付失败，重新加载页面
            // 06.【下单页、订单详情页，超过3000美元不可用paypal支付】（已验）


            // 三：钱包支付问题
            // 01.【网络异常获取钱包余额问题】（已验）
            // -- 打开支付弹窗时，获取余额失败：显示余额为0
            // 02.【余额不足充值并支付】（已验）
            // -- 充值成功后余额足够：支付成功
            // -- 充值成功后余额余额再次不足，后继续充值至余额足够：支付成功
            // 03.【钱包充值限额】（已验）
            // -- 小于1美元：提示The minimum top-up amount is USD 1，支付按钮变灰
            // -- 大于1000美元：提示The maximum single top-up amount is USD 1,000，支付按钮变灰
            // 04.【充值完成后，网络异常导致刷新钱包余额异常问题】
            // -- 暂无交互方案


            // 四：paypal支付问题
            // 01.【支付成功】（已验）
            // -- 点击支付按钮，在新窗口输入密码后，支付完成
            // 02.【新窗口关闭导致的失败】（已验）
            // -- 点击支付按钮，打开新窗口后立即关闭窗口：显示支付错误
            // -- 点击支付按钮，打开新窗口后等待paypal加载完再关闭窗口：pending状态
            // -- 点击支付按钮，打开新窗口后等待paypal支付完成后直接关闭窗口：pending状态等待结果
            // -- 点击支付按钮，打开新窗口后等待paypal支付完成关跳转至返回页面后关闭窗口：pending状态等待结果
            // 03.【网络问题导致的失败】（已验）
            // -- 点击支付按钮时，网络异常：提示连接超时
            // -- 支付完成后，pending状态下，网络异常：继续pending
            // 04.【支付延迟到账delay问题】（已验）
            // -- 下单页面点击paypal支付按钮后，叫小冰修改数据库数据为delayed：订单支付成功，点击OK跳转到订单列表页
            // -- 订单详情点击paypal支付按钮后，叫小冰修改数据库数据为delayed：订单支付成功，点击OK刷新订单详情
            // -- 订单详情点击钱包充值，paypal支付按钮后，叫小冰修改数据库数据为delayed：钱包充值成功，订单余额不变化


            // 五：oceanpay支付问题
            // 01.【加载oceanpay异常】（已验）
            // -- 断网，点击Credit or Debit card按钮前：页面错误
            // 02.【输入银行信息异常】（已验）
            // -- 输入卡号异常：有错误提示
            // -- 输入时间异常：有错误提示
            // -- 输入验证码异常：有错误提示
            // 03.【账单地址异常】（已验）
            // -- 信息为空或格式不对：paynow按钮置灰不可点
            // 03.【账单地址切换】（已验）
            // -- 当下单或订单详情页时：显示Same as shipping address
            // -- 当用户有地址时：显示Address book
            // -- 点击“Same as shipping address”按钮：把订单地址作为账单地址
            // -- 点击“Address book”：显示地址列表，默认选中第一个地址为账单地址，按钮文案改为“Back”
            // -- 点击“地址列表”：使用选中的地址作为账单地址，paynow按钮状态改变
            // -- 点击“Back”：返回到账单输入内容
            // 03.【支付超时，或网络问题】（已验）
            // -- 断网，点击“paynow”：提示支付超时
            // 03.【3d验证】（已验）
            // -- 打开新窗口后关闭窗口：paying
            // -- 输入正确密码：支付成功
            // -- 输入错误密码密码：支付失败，可重新支付

        },

        // 关闭页面
        onClose () {
            if (!this.status) {
                // 已经关闭了
            } else if (/^(init|currency|success|blackuser|batchtip|stock)$/.test(this.status)) {
                this.$emit("close", this.status);
                this.status = "";
            } else {
                this.status = "init";
            }
        },


        // 确认关闭
        currencyConfirm () {
            this.state && this.$store.dispatch('user/updatePopupAccess', { name: 'payment_switching_currency', close: true })
            this.status = 'init';
            this.state = null;
        },

        // 父级拦截
        parentIntercept (handler, option, status) {
            const type = Object.prototype.toString.call(handler);

            if (type === '[object Promise]') {
                // 异步事件
                return handler.then(res => this.parentIntercept(res, option, status))
            } else if (type === '[object Function]') {
                // 函数
                try {
                    return this.parentIntercept(handler(option), option, status)
                } catch (error) {
                    return Promise.reject(String(error));
                }
            } else if (type === '[object String]') {
                // 字符串，表示错误
                return Promise.reject(handler);
            } else if (type === '[object Boolean]' && !handler) {
                // 显示return false，表示取消下一步
                return Promise.reject('Your cancel the next step');
            } else {
                // 其他的，表示正常
                return Promise.resolve(handler);
            }
        },

        // 支付状态变更
        statusChange (info = {}) {

            if (info.action == 'before') {
                // 支付前
                // 获取用户信息，如果
                this.payBefore(info.payment, (opt) => {
                    // 获取用户信息
                    if (opt) {
                        this.$store.dispatch("user/updateUserInfo", { force: true, source: 'order' }).then(res => {
                            if (res.risk_state == 3) {
                                // 黑名单
                                this.status = 'blackuser'
                                info.callback && info.callback(false)
                            } else {
                                this.status = 'paying'
                                info.callback && info.callback(opt)
                            }
                        });
                    } else {
                        info.callback && info.callback(false)
                    }

                })
            } else if (info.action == 'success') {
                // 支付成功
                this.paySuccess(info)
            } else if (info.action == 'reload') {
                // 失败，要重新加载，用于订单状态有异常的情况
                this.status = "";
                this.$emit("close", 'reload');
                this.$uxMessage.warning(info.message);
                // 支付失败
            } else if (info.action == 'cancel') {
                // 取消支付，
                if (info.payment == 'paypal') {
                    // 如果是paypel,则直接close
                    this.$emit("close", this.status);
                } else {
                    // 则返回到初始页面
                    this.status = 'init'
                }
            } else if (info.action == 'stock') {
                // 库存不足
                this.status = 'stock'
                this.stocks = info.stocks || []
            } else {
                // 其他情况
                this.status = info.action
                this.state = info.message
            }
        },


        // 支付前
        async payBefore (payment, callback) {

            // 预处理
            // 设置状态
            this.status = 'before'
            this.option.payment = payment;
            // 执行父级拦截
            this.parentIntercept(this.$listeners.payBefore, this.option, 'before').then(res => {
                if (this.option.codes) {
                    callback && callback(true);
                } else {
                    // 没有id，可能是网络问题
                    // 重新支付
                    this.status = 'network'
                    this.state = () => this.payBefore(payment, callback)
                }
            }).catch(error => {
                // 支付失败，可重新支付
                // -----------------------
                this.payFailure({
                    action: 'error',
                    message: error,
                })

            })
        },


        // 支付失败
        async payFailure (failure) {

            const doFailure = (failure) => {

                // console.log(failure)

                // type: 'error', // 支付失败，不可重新支付
                // type: 'stock',
                // type: 'nolink',
                // type: 'payfor',
                // failure.message && this.$uxMessage.warning(failure.message);

                // cancel|reload|error
                if (!failure) {
                    // 取消,没有反馈，不管
                } else {
                    // type: 'network', // 网络问题，可重新支付
                    // type: ... 其他问题，直接退出
                    this.status = "failure";
                    this.state = failure.message;
                }
            };

            // 执行父级拦截
            this.parentIntercept(this.$listeners.payFailure, failure, 'failure').then(res => {
                // 失败拦截
                doFailure(failure);
            }).catch(error => {
                // 支付失败
                doFailure({
                    action: 'error',
                    message: error,
                })
            })
        },

        // 支付完成
        async paySuccess (success) {
            const doSuccess = () => {
                // 支付完成结束
                this.status = "success";

                // 如果超过3次，则提醒
                if (this.option.action == 'single' && !this.getPopupAccess.payment_switching_batchtip) {
                    this.$http('Order.getPaySuccessCount').then(res => {
                        this.batchtip = res.code === 0 && res.data >= 3
                    })
                }

                // 谷歌统计
                if (/card|paypal/.test(this.option.payment)) {
                    this.$gmeRepore('orderPaid', {
                        value: this.option.amount / 100,
                        transaction_id: this.option.codes,
                    })
                }
            };

            // 执行父级拦截
            this.parentIntercept(this.$listeners.paySuccess, success, 'success').then(res => {
                // 失败拦截
                doSuccess(success);
            }).catch(error => {
                // 支付失败
                this.payFailure({
                    action: 'error',
                    message: error,
                })
            })
        },

        // 价格格式化
        getPriceFormat (val) {
            let value = parseFloat(val / 100) || 0;
            return value.toFixed(2);
        },
    },

    beforeDestroy () {
        this.status = "init";
    },
};
</script>
<style lang="scss" scoped>
.order-payment {
    .order-payment-close {
        z-index: 1;
        position: absolute;
        right: 4px;
        top: 4px;
        width: 24px;
        height: 24px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #555;
        transition: all 0.3s;
        cursor: pointer;
        border-radius: 4px;

        svg {
            width: 10px;
            height: 10px;
        }

        &:hover {
            background-color: rgba(255, 0, 0, 0.1);
            color: #8c1c14;
        }
    }

    &[status='paying'] {
        display: none !important;
    }
}

.order-payment-currency {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 20px;

    figure {
        margin-top: 20px;
        width: 80px;
        height: 80px;

        img {
            width: 100%;
            height: 100%;
        }
    }

    h2 {
        margin-top: 8px;
        font-size: 16px;
        font-family: Roboto-Medium, Roboto;
        font-weight: normal;
        color: #000000;
        line-height: 18px;
    }

    p {
        margin-top: 16px;
        max-width: 280px;
        font-size: 14px;
        font-family: Roboto-Regular, Roboto;
        font-weight: 400;
        color: #000000;
        line-height: 20px;
        text-align: center;
    }

    label {
        margin-top: 48px;
        width: 100%;
        max-width: 280px;
        display: flex;
        flex-direction: row;
        align-items: center;
        height: 24px;
        font-size: 14px;
        color: #000000;
        line-height: 14px;
        position: relative;
        cursor: pointer;

        input {
            position: absolute;
            width: 0;
            height: 0;
            opacity: 0;

            &:checked+i {
                border-color: #ea4c89;
                background-color: #ea4c89;
                text-indent: -1px;
                color: #fff;
            }
        }

        i {
            display: inline-block;
            vertical-align: top;
            width: 16px;
            height: 16px;
            box-sizing: border-box;
            background: #ffffff;
            border-radius: 2px;
            margin-right: 8px;
            border: 2px solid #919191;
            font-size: 14px;
            text-align: center;
            line-height: 12px;
            text-indent: -99em;
            overflow: hidden;
        }

        span {
            display: inline-block;
            vertical-align: top;
            line-height: 24px;
        }
    }

    button {
        margin-top: 24px;
        margin-bottom: 6px;
        height: 38px;
        width: 100%;
        max-width: 280px;
    }
}

.order-payment-before {
    box-sizing: border-box;
    display: flex;
    flex-wrap: wrap;
    background: #ffffff;
    border-radius: 8px;
    position: relative;
    justify-content: center;
    max-width: 856px;
    padding: 0 20px 28px;

    &>.order-payment-before-currency {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        font-weight: normal;
        justify-content: center;
        padding-top: 40px;
        padding-bottom: 16px;
        border-bottom: 1px dashed rgba(151, 151, 151, 0.16);

        em {
            margin-right: 4px;
        }

        em,
        .currency-rate {
            font-size: 14px;
            font-family: Roboto-Medium, Roboto;
            font-weight: 500;
            color: #000000;
            line-height: 16px;
        }

        &>span {
            width: 100%;
            font-size: 12px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #555555;
            margin-top: 6px;
            line-height: 14px;
            text-align: center;
        }
    }

    &>h3 {
        width: 100%;
        height: 80px;
        display: flex;
        justify-content: center;
        align-items: center;

        &>img {
            width: 26px;
            height: 26px;
        }

        span {
            line-height: 26px;
            font-size: 24px;
            font-family: Roboto-Medium, Roboto;
            font-weight: 500;
            color: #000000;
            margin-left: 4px;
        }
    }

    &[currency='USD'] {
        .order-payment-before-currency {
            display: none;
        }

        &>h3 {
            height: 146px;
        }
    }

    .payment-wallet {
        width: calc(50% - 16px);
        margin: 0 8px;
        border: 1px solid #eeeeee;
        box-sizing: border-box;
        border-radius: 8px;
    }

    .order-payment-other {
        width: calc(50% - 16px);
        margin: 0 8px;
        border: 1px solid #eeeeee;
        box-sizing: border-box;
        border-radius: 8px;
    }

    &.no-wallet {
        width: 376px;
        height: 428px;

        &>h3 {
            img {
                width: 24px;
                height: 24px;
            }

            span {
                font-size: 20px;
            }
        }

        .order-payment-other {
            width: 100%;
            margin: 0;
            border: none;
            padding: 12px;


            &::v-deep .order-payment-group {
                justify-content: flex-end;
            }



            &::v-deep h4 {
                display: none;
            }
        }
    }
}

.order-payment-other {
    padding: 32px 24px 36px;
    display: flex;
    flex-direction: column;
    align-items: center;
    background: #ffffff;
    border-radius: 8px;

    h4 {
        margin-bottom: 48px;
        height: 26px;
        font-size: 18px;
        font-weight: 500;
        color: #000000;
        line-height: 26px;
        font-family: Roboto-Medium, Roboto;
    }

    .order-payment-group {
        display: flex;
        flex-direction: column;
        justify-content: center;
        max-width: 312px;
        width: 100%;
        height: 106px;
        overflow: hidden;

        &>div+div {
            margin-top: 10px;
        }
    }

    p {
        margin-top: 12px;
        user-select: none;
        box-sizing: border-box;
        max-width: 312px;
        width: 100%;
        min-height: 64px;
        background: #f3f9f3;
        border-radius: 4px;
        padding: 14px 14px 14px 58px;
        font-size: 14px;
        color: #69a274;
        line-height: 18px;
        position: relative;
        font-family: Roboto-Regular, Roboto;
        font-weight: 400;

        &::before {
            content: '';
            display: block;
            position: absolute;
            top: 50%;
            left: 12px;
            transform: translateY(-50%);
            width: 36px;
            height: 36px;
            background-image: url('https://img.podpartner.com/static/images-20230202/payment-safe.png');
            background-size: 36px 36px;
        }
    }
}

.order-payment-success,
.order-payment-failure,
.order-payment-network {
    width: 320px;
    height: 414px;
    display: flex;
    flex-direction: column;
    align-items: center;

    &>figure {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        img {
            width: 80px;
            height: 80px;
        }

        strong {
            margin: 16px 20px 0;
            font-size: 18px;
            color: #000000;
            line-height: 28px;
            text-align: center;
        }

        span {
            margin: 8px 20px;
            font-size: 14px;
            color: #555555;
            line-height: 18px;
            text-align: center;
            white-space: pre-wrap;
            word-break: break-word;
        }
    }

    &>button {
        height: 38px;
        line-height: 36px;
        width: 280px;
        margin-bottom: 30px;
        font-size: 14px;
    }
}

.order-payment-failure>figure img {
    width: 60px;
    height: 60px;
}
</style>
